<?php

namespace app\api\controller;

use app\admin\model\ykw\Specialty;
use app\admin\model\ykw\Subject;
use app\admin\model\ykw\Article;
use app\admin\model\ykw\Img;
use app\admin\model\ykw\OrderForm;
use app\admin\model\ykw\Specialtys;
use app\admin\model\ykw\University;
use app\admin\model\ykw\UserInfo;
use app\admin\model\ykw\WxUser;
use app\common\controller\Api;

use app\admin\model\Volunteer;
use app\common\model\Area;
use app\common\model\Category;
use app\common\model\Config;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use mysql_xdevapi\Result;
use PhpOffice\PhpSpreadsheet\Reader\Xls\MD5;
use function PHPSTORM_META\elementType;
use function PHPSTORM_META\type;
use think\Cache;
use think\Console;
use think\Request;
use think\response\Json;

use EasyWeChat\Factory;

/**
 * 业务接口
 */
class Ykw extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    //电话
    public function dhhm()
    {
        return \json(Config::get(['name' => 'dhhm'])['value']);
    }

    //一键了解公费留学
    public function yjlj()
    {
        $data = Article::get(Config::get(['name' => 'yjlj'])['value']);
        $data->ptype = Category::get($data['category_id'])['type'];
        return json($data);
    }


    /**
     * 轮播图
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function slideshow()
    {
        $data = Img::order('weigh desc')->select();
        $article = Article::column('id category_id');
        foreach ($data as &$d) {
            $d = $d->toArray();
            $i = $article[$d['article_id']];
            $d['type'] = Category::where(['id' => $i])->column('type')[0];
        }
        return json($data);
    }


    /**
     * 一级列表
     * 返回文章或问答列表
     * @param $key 关键字 可选 faq  article  对应着问答和文章
     * @return Category[]|false
     * @throws \think\exception\DbException
     */
    public function particle($key, $page, $pageSize = 10)
    {
        return json(Category::where(['type' => $key])->page($page, $pageSize)->order('weigh desc')->select());
    }


    /**
     * 二级列表
     * @param $id
     * @return Json
     * @throws \think\exception\DbException
     */
    public function articleList($id, $page, $pageSize = 10)
    {
        return json(Article::where(['category_id' => $id, 'switch' => 1])->order('weigh desc')->page($page, $pageSize)->select());
    }


    /**
     * 区块列表
     */
    public function qkList($id){
        return json(Category::where(['pid' => $id])->order('weigh desc')->select());
    }


    /**
     * 返回文章内容
     * @param $id
     * @return Article|null
     * @throws \think\exception\DbException
     */
    public function article($id)
    {
        return json(Article::get(['id' => $id]));
    }

    /**
     * 科目
     * @return Json
     * @throws \think\exception\DbException
     */
    public function subject()
    {
        return json(Subject::all());
    }

    /**
     * 专业
     * @return Json
     * @throws \think\exception\DbException
     */
    public function specialty()
    {
        //得到专业根据权重排序
        return json(Specialty::order('weigh desc')->select());

    }


    /**
     * 检索接口
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function search()
    {
        $this->request = request();
        if ($this->request->isPost()) {
            if (!$this->request->post('out_trade_no')) {
                $data = $this->search2($this->request->post('zhfpm'), $this->request->post('yxzy'));
                if ($data) {
                    $post = $this->request->post();
                    $post['subject_id'] = $post['yskl'];
                    $post['specialty_id'] = $post['yxzy'];
                    unset($post['yskl']);
                    unset($post['yxzy']);
                    unset($post['sessionKey']);

                    $WxUser = new WxUser;
                    $user = json_decode(Cache::get($this->request->param('sessionKey')));
                    $post['openid'] = $user->openid;
                    $WxUser->save($post);
                }
            }
            $data = OrderForm::get(['out_trade_no' => $this->request->post('out_trade_no')]);
            if ($data && $data->status === '已支付') {
                $u = WxUser::get(['out_trade_no' => $this->request->post('out_trade_no')]);

                return $this->search2($u['zhfpm'], $u['specialty_id']);
            } elseif ($data && $data->status === '未支付') {
                $orderForm = [
                    'body' => $data->body,
                    'out_trade_no' => $data->out_trade_no,
                    'total_fee' => $data->total_fee * 100,
                    //            'spbill_create_ip' => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
                    //            'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                    'trade_type' => $data->trade_type, // 请对应换成你的支付方式对应的值类型
                    'openid' => $data->openid,
                ];
                $app = Factory::payment(config('xcx'));
                $result = $app->order->unify($orderForm);

                if ($result['return_code'] == 'SUCCESS' && $result['return_code'] == 'SUCCESS') {
                    $jssdk = $app->jssdk;
                    $con = $jssdk->bridgeConfig($result['prepay_id'], false);
                    //订单号
                    $con['out_trade_no'] = $orderForm['out_trade_no'];
                    return \json($con);
                }
                return json('0', '统一下单接口请求失败');
            } else {
                return $this->zf();
            }
        }
    }

    //生成订单
    public function scdd()
    {
        $count = UserInfo::get(['openid' => $this->wxuser->openid]);

        if (!Config::get(['name' => 'zfkg'])['value']) {
            $orderForm = [
                'body' => '易考网-检索支付',
                'out_trade_no' => time(),
                'total_fee' => 0,
                //            'spbill_create_ip' => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
                //            'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'trade_type' => '支付关闭', // 请对应换成你的支付方式对应的值类型
                'openid' => $this->wxuser->openid,
            ];
        } else if ($count->free_count) {
            $count->free_count -= 1;
            $count->save();
            $orderForm = [
                'body' => '易考网-检索支付',
                'out_trade_no' => time(),
                'total_fee' => 0,
                //            'spbill_create_ip' => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
                //            'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'trade_type' => '分享', // 请对应换成你的支付方式对应的值类型
                'openid' => $this->wxuser->openid,
            ];
        } else {
            $orderForm = [
                'body' => '易考网-检索支付',
                'out_trade_no' => time(),
                'total_fee' => Config::get(['name' => 'zfje'])['value'] * 100,
                //            'spbill_create_ip' => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
                //            'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'trade_type' => '付费', // 请对应换成你的支付方式对应的值类型
                'openid' => $this->wxuser->openid,
            ];

        }

        //生成用户数据
        $post = $this->request->post();
        $post['subject_id'] = $post['yskl'];
        $post['specialty_id'] = $post['yxzy'];
        unset($post['yskl']);
        unset($post['yxzy']);
        unset($post['sessionKey']);
        $post['openid'] = $this->wxuser->openid;
        $post['out_trade_no'] = $orderForm['out_trade_no'];
        $post['create_time'] = date('Y-m-d H:i:s', time());
        $post['nickname'] = $this->wxuser->name;
        $post['image'] = $this->wxuser->tx;
//        $post['specialty_id']=$post['specialty_id']==0?'全部':$post['specialty_id'];
        $WxUser = WxUser::create($post);


        $orderForm['status'] = $orderForm['trade_type'] == '付费' ? '未支付' : '无需支付';
        $orderForm['total_fee'] = $orderForm['total_fee'] / 100;
        $o = OrderForm::create($orderForm);

        return json(['out_trade_no' => $o->out_trade_no, 'trade_type' => $o->trade_type]);

    }

    //支付
    public function zf2()
    {
        $o = OrderForm::get(['out_trade_no' => $this->request->post('out_trade_no')]);
        if ($o && !($o->trade_type === '付费')) {
            return resoultJson('0', '此订单无需付费');
        }

        $OrderForm = OrderForm::get(['out_trade_no' => $this->request->post('out_trade_no')]);
        $app = Factory::payment(config('xcx'));
        $result = [
            'body' => $OrderForm->body,
            'out_trade_no' => $OrderForm->out_trade_no,
            'total_fee' => $OrderForm->total_fee * 100,
            //            'spbill_create_ip' => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            //            'notify_url' => 'https://pay.weixin.qq.com/wxpay/pay.action', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $OrderForm->openid,
        ];

        //(http_response_code() expects parameter 1 to be integer, string given)是这个微信结构触发的异常
        $result = $app->order->unify($result);


        if ($result['return_code'] == 'SUCCESS' && $result['return_code'] == 'SUCCESS') {
            $jssdk = $app->jssdk;
            $con = $jssdk->bridgeConfig($result['prepay_id'], false);
            //订单号

            return json($con);
        }

        return json('0', '统一下单接口请求失败');
    }

    public function searchPd()
    {
        $o = OrderForm::get(['out_trade_no' => $this->request->post('out_trade_no')]);
        if ($o && $o->trade_type === '付费') {
            if ($o->status === '已支付') {
                $data = WxUser::get(['out_trade_no' => $this->request->post('out_trade_no'),]);
                return $this->search2($data);
            } else {
                return resoultJson(0, '订单未支付');
            }
        }

        if ($o && ($o->trade_type === '支付关闭' || $o->trade_type === '分享')) {
            $data = WxUser::get(['out_trade_no' => $this->request->post('out_trade_no'),]);
            return $this->search2($data);
        }
        return resoultJson(0, '单号错误');

    }


    //查询
    private function search2($data)
    {
        $zhfpm = $data->zhfpm;
        $yxzy = $data->specialty_id;

        //取出配置文件的条件
        $jstj = json_decode(Config::get(['name' => 'jstj'])['value']);

        if ($yxzy == 135) {
            //冲
            $c = Volunteer::where(['switch' => 1])->where('lowest_rank', ['<=', $zhfpm + $jstj->冲下限], ['>=', $zhfpm - $jstj->冲上限], "AND")->order('lowest_rank desc')->limit(3)->select();
            $c = array_map(function ($n) {

                return $n->toArray();

            }, $c);
            array_multisort($c, array_column($c, 'lowest_rank'));

            //稳
            $w = Volunteer::where(['switch' => 1])->where('lowest_rank', ['>=', $zhfpm + $jstj->稳上限], ['<=', $zhfpm + $jstj->稳下限], "AND")->order('lowest_rank asc')->limit(6)->select();
            //保
            $b = Volunteer::where(['switch' => 1])->where('lowest_rank', ['>=', $zhfpm + $jstj->保上限], ['<=', $zhfpm + $jstj->保下限], "AND")->order('lowest_rank asc')->limit(3)->select();
        } else {

            //冲
            $c = Volunteer::where(['switch' => 1])->where(['specialty_id' => $yxzy])->where('lowest_rank', ['<=', $zhfpm + $jstj->冲下限], ['>=', $zhfpm - $jstj->冲上限], "AND")->order('lowest_rank desc')->limit(3)->select();
            //根据最低排名从小到大排序
            $c = array_map(function ($n) {

                return $n->toArray();

            }, $c);
            array_multisort($c, array_column($c, 'lowest_rank'));

            //稳
            $w = Volunteer::where(['switch' => 1])->where(['specialty_id' => $yxzy])->where('lowest_rank', ['>=', $zhfpm + $jstj->稳上限], ['<=', $zhfpm + $jstj->稳下限], "AND")->order('lowest_rank asc')->limit(6)->select();
            //保
            $b = Volunteer::where(['switch' => 1])->where(['specialty_id' => $yxzy])->where('lowest_rank', ['>=', $zhfpm + $jstj->保上限], ['<=', $zhfpm + $jstj->保下限], "AND")->order('lowest_rank asc')->limit(3)->select();
        }
        $sj = ['c' => $c, 'w' => $w, 'b' => $b];
        foreach ($sj as &$d) {
            foreach ($d as &$c) {
                $c['subject_id'] = Subject::get($c['subject_id'])['subject'];
                $c['specialtys_id'] = Specialtys::get($c['specialtys_id'])['specialty'];
                $c['specialty_id'] = Specialty::get($c['specialty_id'])['specialty'];
                $c['university_id'] = University::get($c['university_id'])['university'];
            }
        }
        $a=[
            'id'=>'',
            'subject_id'=>'',
            'specialtys_id'=>'',
            'specialty_id'=>'',
            'tuition'=>'',
            'planned_quantity'=>'',
            'university_id'=>'',
            'grade'=>'',
            'lowest_rank'=>'',
            'switch'=>'',
            'create_time'=>'',
            'update_time'=>'',
        ];

        //参数不足是补空参数，也就是$a
        if (!(count($sj['c'])==3)){
            $count= 3 - count($sj['c']);
            for ($i = 0; $i < $count; $i++) {
                $sj['c'][] = $a;
            }
        }
        if (!(count($sj['w'])==6)){
            $count= 6 - count($sj['w']);
            for ($i = 0; $i < $count; $i++) {
                $sj['w'][] = $a;
            }
        }
        if (!(count($sj['b'])==3)){
            $count= 3 - count($sj['b']);
            for ($i = 0; $i < $count; $i++) {
                $sj['b'][]= $a;
            }
        }

        $data->content = json_encode($sj);
        $data->save();
        return json($sj);
    }

    //上传用户头像姓名
    public function userInfo($name, $tx)
    {
        $data = json_decode(Cache::get($this->request->param('sessionKey')));
        $data->name = $name;
        $data->tx = $tx;
        Cache::set($this->request->param('sessionKey'), json_encode($data), 7200);
        $user = UserInfo::get(['openid' => $this->wxuser->openid]);
        $user->nickname = $name;
        $user->image = $tx;
        if ($user->save()) {
            return resoultJson($user->save(), '成功');
        }
        return resoultJson('0', '数据无变化');
    }

    //历史记录
    public function userContent()
    {
        $subject = Subject::column('id,subject');
        $specialty = Specialty::column('id,specialty');

        $specialty[0] = '全部';
        $data = WxUser::where(['openid' => $this->wxuser->openid])->select();
        foreach ($data as &$v) {
            $v = $v->toArray();
            foreach ($v as $c => &$b) {
                if ($c == 'subject_id') {
                    $b = $subject[$b];
                }
                if ($c == 'specialty_id') {
                    $b = $specialty[$b];
                }
            }
        }
        return json($data);
    }

    //增加免费次数
    public function getFreeCount()
    {
        $user = UserInfo::get(['openid' => $this->wxuser->openid]);
        $user->free_count += 1;

        if ($user->save()) {
            resoultJson(1, '增加成功');
        }
    }
}

